<!--审核组页面-->
<template>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="text" @click="addReviewGroup" >
        <el-icon><Plus /></el-icon>
        新增审查组
    </el-button>
    </div>  
    <el-table
        :data="reviewData"
        style="width: 100%"
        row-key="id"
        border
    >
        <el-table-column prop="name" label="审核组名称" />
        <el-table-column label="绑定成员">
          <template v-slot="scope">
            <!-- 通过逗号连接数组中的成员用户名 -->
            <span v-for="(user, index) in scope.row.users" :key="user.id">
              {{ user.personname }}
              <span v-if="index < scope.row.users.length - 1">| </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="描述" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
            <el-button
            type="primary"
            :icon="Edit"
            size="small"
            @click="openEditDialog(scope.row)"
            title="编辑"
            >编辑</el-button>
            <el-button
            type="danger"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="removeCategory(scope.row.id)"
            title="删除"
            >删除</el-button>
        </template>
        </el-table-column>
  </el-table>
    <el-dialog v-model="dialogFormVisible" title="新增审核组" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        
        <el-form-item label="审核组名称" prop="name">
          <el-input v-model="form.name" placeholder="请输组名称" />
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入描述" />
        </el-form-item>

        <el-form-item label="绑定用户" prop="users">
          <el-select v-model="form.users" multiple placeholder="请选择">
            <el-option
              v-for="item in userinfo"
              :key="item.id"
              :label="item.personname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
    v-model="dialogEditVisible"
    :title="修改审核组"
    width="500px"
    >
    <el-form :model="form" label-width="80px">
        <el-form-item label="审核组名称">
        <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.remark" />
        </el-form-item>
        <el-form-item label="绑定用户" prop="users">
          <el-select v-model="form.users" multiple placeholder="请选择">
            <el-option
              v-for="item in userinfo"
              :key="item.id"
              :label="item.personname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogEditVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUpdateCategory">保存</el-button>
    </template>
    </el-dialog>
</template>
<script setup>

import {toRefs,onBeforeMount,onMounted,reactive,ref,computed} from "vue"
import { ElMessage,ElForm, ElFormItem, ElInput, ElButton,ElMessageBox } from 'element-plus';
import { Plus,Minus } from '@element-plus/icons-vue'
import { getKnowledgeReviewGroupInfoHandler,delKnowledgeReviewGroupInfoHandler,addKnowledgeReviewGroupInfoHandler,updateKnowledgeReviewGroupInfoHandler } from "../../api/knowledge.js"
import { base64Decode } from "../../utils/base64.js"
import { getUsersAllList } from "../../api/user.js"
const data = reactive({
    reviewData: [],
})
const {reviewData} = toRefs(data)
// const isEditable = ref(false)
const dialogFormVisible = ref(false)
const dialogEditVisible = ref(false)
const formRef = ref(null)
const userinfo = ref([])
const form = ref({
  id: null,
  name: null,
  remark: '',
  users: [],
})
const loadConfig = async()=>{
  try {
      const response = await getKnowledgeReviewGroupInfoHandler()
      console.log("response==============20250908",response.data.data)
      if (response.data.data) {
          // categoryData.value = base64Decode(response.data.data.assetCategory)
          reviewData.value = response.data.data.knowledgereviewData
          console.log("reviewData==========20250908",reviewData.value)
      }
  }
  catch(error){
      console.error("保存配置失败:", error)
      
  }
}


const fetchUserData = async () => {
  try {
    const response = await getUsersAllList()
    if (response.data.data) {
      const base64String = response.data.data.userlist
      const decodedBytes = atob(base64String);
      // 将字节串转换为 Uint8Array
      const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
      // 使用 TextDecoder 解码为字符串
      const decoder = new TextDecoder("utf-8");
      const decodedString = decoder.decode(uint8Array);
      console.log("userinfo=============20250908", decodedString)

      // 解析 decodedString 为 JSON 对象或数组
      userinfo.value = JSON.parse(decodedString);
      console.log("formuserinfo=============20250908", userinfo.value)
    }
  } catch (error) {
    console.error("获取用户失败:", error)
    ElMessage({
      message: error?.response?.data?.message || "查询失败，请重试",
      type: 'error',
    })
  }
}
const addReviewGroup=()=>{
  dialogFormVisible.value=true
  // fetchUserData()
}

const submitForm = async() => {
    try{
        const valid = await formRef.value.validate()
        if(valid){
            console.log('新增分类数据:', form.value)
            const usersToSubmit = form.value.users.map(userid => ({ userid }));
            console.log('新增审核组数据:', usersToSubmit)
            form.value.users=usersToSubmit
            console.log('新增分类数据:', form.value)
            const res = await addKnowledgeReviewGroupInfoHandler(form.value)
            if (res.data) {
                console.log("res.data====20250821",res.data)
                ElMessage({
                message: res.data.message,
                type: 'success'})
            }
            dialogFormVisible.value = false
            form.value=[]
            userinfo.value=[]
            await loadConfig()
        }
    } catch(error){
        console.error("添加失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "添加失败，请重试",
                    type: 'error',
        })
    }
  
}
const removeCategory=async(id)=>{
    try {
        console.log("id=======20250813",id)
        const intId = Number(id)
        const response = await delAssetCategoryInfoHandler(intId)
        
        if (response.data) {
            ElMessage({
                    message: response.data.message,
                    type: 'success',
            })
            console.log("delcategoryData==========20250821",response.data)
            await loadConfig()
            
        }
    } catch(error) {
        console.error("删除失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "删除失败，请重试",
                    type: 'error',
        })
        // throw err // 如果需要让调用方知道错误
    }
    
}
const openEditDialog=(row)=>{
    fetchUserData()
    console.log("row======20250909",row)
    form.value={...row}
    console.log("userinfo================090900000",userinfo.value)
    console.log("from.value=============20250909",form.value.users)
    const payload = form.value.users.map(u => u.userId)
    // form.value.users=payload
    form.value.users = payload
    // userinfo.value=
    dialogEditVisible.value = true
}
const saveUpdateCategory=async()=>{
    try {
        const id=form.value.id
        console.log("==============20250822",id)
        const payloadUsers = form.value.users.map(userId => {
          const user = userinfo.value.find(u => u.userId === userId);
          return { userId };
        });
        const payload = {
          id: form.value.id,
          name: form.value.name,
          remark: form.value.remark,
          users: payloadUsers
        };
      
        const res = await updateKnowledgeReviewGroupInfoHandler(id,payload)
        if (res.data){
            ElMessage({
                    message: res.data.message,
                    type: 'success',
            })
            console.log("updatecategoryData==========20250822",res.data)
            dialogEditVisible.value = false

            await loadConfig()
        }
    }catch(error){
        console.error("更新失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "更新失败，请重试",
                    type: 'error',
        })
    }
}
onMounted(() => {
  loadConfig();
});
onBeforeMount(()=>{
  fetchUserData()
})
</script>